<template>
  <div class="contain">
    <div class="key">
      <div class="top">
        <el-select
          v-model="chartKeyType"
          placeholder="请选择图表类型"
          style="width: 200px; margin-left: 20px"
        >
          <el-option label="柱状图" value="bar"></el-option>
          <el-option label="饼图" value="pie"></el-option>
        </el-select>
      </div>
      <div ref="queryCharts" class="queryCharts"></div>
    </div>
    <div class="enterprise">
      <div class="top">
        <el-select
          v-model="chartEnterpriseType"
          placeholder="请选择图表类型"
          style="width: 200px; margin-left: 20px"
        >
          <el-option label="柱状图" value="bar"></el-option>
          <el-option label="饼图" value="pie"></el-option>
        </el-select>
      </div>
      <div ref="enterpriseCharts" class="enterpriseCharts"></div>
    </div>
    <div class="comment">
      <div class="top">
        <el-date-picker
          v-model="commentDate"
          type="daterange"
          range-separator="-"
          start-placeholder="Start date"
          end-placeholder="End date"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disableFutureDates"
        />
        <el-select
          v-model="chartCommentType"
          placeholder="请选择图表类型"
          style="width: 200px; margin-left: 20px"
        >
          <el-option label="柱状图" value="bar"></el-option>
          <el-option label="饼图" value="pie"></el-option>
        </el-select>
      </div>
      <div ref="commentCharts" class="commentCharts"></div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { getTopKeywords, getTopSearchedEnterprises, getDailyCommentStats } from '@/api/statistics'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

const chartKeyType = ref('bar')
const chartEnterpriseType = ref('bar')
const chartCommentType = ref('bar')
const queryCharts = ref(null)
const topKeyData = ref([])
const topEnterprise = ref([])
const commentData = ref([])
const enterpriseCharts = ref(null)
const commentCharts = ref(null)
const commentDate = ref([
  dayjs().format('YYYY-MM-DD'), // 默认选中当天
  dayjs().format('YYYY-MM-DD'),
])
watch(chartKeyType, () => {
  renderKeyChart()
})
watch(chartCommentType, () => {
  renderCommentChart()
})
watch(chartEnterpriseType, () => {
  renderEnterpriseChart()
})
const renderKeyChart = () => {
  const dates = topKeyData.value.map((item) => item.keyword)
  const values = topKeyData.value.map((item) => item.searchCount)
  const option =
    chartKeyType.value === 'bar'
      ? {
          title: {
            text: '用户查询关键词',
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            data: dates,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '关键词次数',
              type: 'bar',
              data: values,
              barWidth: 40, // 设置柱子的固定宽度（可以调整）
              label: {
                show: true, // 显示标签
                position: 'top', // 标签位置
                formatter: '{c}次', // 在柱子上显示百分数
              },
            },
          ],
        }
      : {
          title: {
            text: '用户查询关键词',
            left: 'center',
          },
          tooltip: {
            trigger: 'item',
          },
          series: [
            {
              name: '关键词次数',
              type: 'pie',
              radius: '50%',
              data: topKeyData.value.map((item) => ({
                value: item.searchCount,
                name: item.keyword,
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
              },
            },
          ],
        }
  const chart = echarts.init(queryCharts.value)
  chart.setOption(option, true)
}
const getTopKey = async () => {
  const res = await getTopKeywords()
  if (res.status === 200 || res.status === 201) {
    topKeyData.value = res.data.data
    renderKeyChart()
  }
}
const renderEnterpriseChart = () => {
  const dates = topEnterprise.value.map((item) => item.enterprise.name)
  const values = topEnterprise.value.map((item) => item.searchCount)
  const option =
    chartEnterpriseType.value === 'bar'
      ? {
          title: {
            text: '用户查询企业频率',
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            data: dates,

            axisLabel: {
              interval: 0, // 不省略任何标签
              margin: 8, // 标签与轴线的距离
              formatter: function (value) {
                return value.length > 5 ? value.substring(0, 5) + '\n' + value.substring(5) : value
              },
            },
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '企业查询频率',
              type: 'bar',
              data: values,
              barWidth: 40, // 设置柱子的固定宽度（可以调整）
              label: {
                show: true, // 显示标签
                position: 'top', // 标签位置
                formatter: '{c}次', // 在柱子上显示百分数
              },
            },
          ],
        }
      : {
          title: {
            text: '用户查询企业频率',
            left: 'center',
          },
          tooltip: {
            trigger: 'item',
          },
          series: [
            {
              name: '企业查询频率',
              type: 'pie',
              radius: '50%',
              data: topEnterprise.value.map((item) => ({
                name: item.enterprise.name,
                value: item.searchCount,
              })),
            },
          ],
        }
  const chart = echarts.init(enterpriseCharts.value)
  chart.setOption(option, true)
}
const getTopEnterprise = async () => {
  const res = await getTopSearchedEnterprises()
  if (res.status === 200 || res.status === 201) {
    topEnterprise.value = res.data.data
    renderEnterpriseChart()
  }
}
const getCommentData = async () => {
  const res = await getDailyCommentStats({
    startDate: commentDate.value[0],
    endDate: commentDate.value[1],
  })
  if (res.status === 200 || res.status === 201) {
    commentData.value = res.data.data
    renderCommentChart()
  }
}
watch(commentDate, () => {
  if (commentDate.value.length === 2) {
    const startDate = dayjs(commentDate.value[0])
    const endDate = dayjs(commentDate.value[1])
    const diffDays = endDate.diff(startDate, 'day')
    if (diffDays > 7) {
      ElMessage.warning('时间范围不能超过 7 天，请重新选择！')
      commentData.value = []
      commentDate.value = []
      return
    }
  }
  getCommentData()
})
const renderCommentChart = () => {
  const dates = commentData.value.map((item) => item.date)
  const values = commentData.value.map((item) => item.commentCount)
  const option =
    chartCommentType.value === 'bar'
      ? {
          title: {
            text: '用户评论频率',
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            data: dates,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '评论频率',
              type: 'bar',
              data: values,
              barWidth: 40, // 设置柱子的固定宽度（可以调整）
              label: {
                show: true, // 显示标签
                position: 'top', // 标签位置
                formatter: '{c}次', // 在柱子上显示百分数
              },
            },
          ],
        }
      : {
          title: {
            text: '用户评论频率',
            left: 'center',
          },
          tooltip: {
            trigger: 'item',
          },
          series: [
            {
              name: '评论频率',
              type: 'pie',
              radius: '50%',
              data: commentData.value.map((item) => ({
                name: item.date,
                value: item.commentCount,
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
              },
            },
          ],
        }

  const chart = echarts.init(commentCharts.value)
  chart.setOption(option, true)
}
const disableFutureDates = (date) => {
  return date.getTime() > new Date().getTime() // 禁止选择今天之后的日期
}
onMounted(() => {
  getTopKey()
  getTopEnterprise()
  getCommentData()
})
</script>

<style lang="scss" scoped>
.contain {
  padding: 30px;
  .queryCharts {
    margin-top: 20px;
    width: 1000px;
    height: 400px;
  }
  .enterpriseCharts {
    margin-top: 20px;
    width: 1000px;
    height: 400px;
  }
  .commentCharts {
    margin-top: 20px;
    width: 1000px;
    height: 400px;
  }
}
</style>

